package com.zy.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
/**
 * JSON数据工具类
 * 
 * @author jyx
 * @date:2013-11-16
 * @version : v1.0
 * 
 */
public class GsonHelper {
	private static Gson gson = new Gson();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String s = "[{\"invoiceId\":\"BN-FP-20131216-004\",\"invoiceNum\":null,\"invoiceNowFlag\":null,\"invoiceUnifyFlag\":null,\"operateUser\":1,\"checkFlag\":null,\"checkStatus\":null,\"checkUser\":null,\"checkContent\":null,\"createTime\":1387177854000,\"checkTime\":null,\"remark\":null,\"outId\":\"BN-CK-20131216-004\",\"warnId\":null,\"operateUserStr\":\"admin\",\"checkUserStr\":\"admin\",\"createTimeStr\":\"2013-12-16 15:10:54\",\"checkTimeStr\":null},{\"invoiceId\":\"BN-FP-20131123-002\",\"invoiceNum\":null,\"invoiceNowFlag\":2,\"invoiceUnifyFlag\":1,\"operateUser\":null,\"checkFlag\":null,\"checkStatus\":null,\"checkUser\":null,\"checkContent\":null,\"createTime\":1386754889000,\"checkTime\":null,\"remark\":null,\"outId\":null,\"warnId\":null,\"operateUserStr\":null,\"checkUserStr\":null,\"createTimeStr\":\"2013-12-11 17:41:29\",\"checkTimeStr\":null}]";
//		List<InvoiceNote> list = GsonUtil.fromJson(s, ArrayList.class);
		
//		List<InvoiceNote> list2 = GsonUtil.fromJson(s, new TypeToken<List<InvoiceNote>>(){}.getType());
//		System.out.println(list.size());
//		System.out.println(list2.size());
		
		
//		System.out.println(GsonUtil.toJson(list));
//		System.out.println(GsonUtil.toJson(list2));
		
//		System.out.println(list2.get(0).getInvoiceId());
	}

	/**
	 * 对象转换为json字符串
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj){
		return gson.toJson(obj);
	}
	
	 /** 
     * json字符串转成对象 
     * @param str   
     * @param type 
     * @return  
     */  
    public static <T> T fromJson(String json, Type type) {  
    	T t = gson.fromJson(json, type);
        return t;  
    }  
  
    /** 
     * json字符串转成对象 
     * @param str   
     * @param type  
     * @return  
     */  
    public static <T> T fromJson(String json, Class<T> type) {  
    	T t = gson.fromJson(json, type);
        return t;  
    }  
	
	/**
	 * 对象转换为格式化json
	 * @param obj
	 * @return
	 */
	public static String toJsonFormat(Object obj){
		String uglyJSONString = gson.toJson(obj);
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(uglyJSONString);
		String prettyJsonString = gson.toJson(je);
		return prettyJsonString;
	}

	
	public static Gson getGson(){
		return gson;
	}
	
}

